package com.plat.net.udp;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 构建初始化服务端
 */
public class UDPServer {
    Logger logger = LoggerFactory.getLogger(UDPServer.class);

    //服务启动对象
    private Bootstrap server;
    //接受连接的线程组
    private NioEventLoopGroup bossGroup;

    private int port;


    public UDPServer(int port) {
        init(port);
    }

    private void init(int port) {
        this.bossGroup = new NioEventLoopGroup();
        this.server = new Bootstrap();
        this.port = port;
    }

    public void buildServer() {
        this.server.group(bossGroup);
        server.channel(NioDatagramChannel.class)
                //处理打印日志
                .handler(new LoggingHandler(LogLevel.INFO))
                .handler(new UDPChannelInitial())
                // 广播
                .option(ChannelOption.SO_BROADCAST, true)
                // 设置读缓冲区为2M
                .option(ChannelOption.SO_RCVBUF, 2048 * 1024)
                // 设置写缓冲区为1M
                .option(ChannelOption.SO_SNDBUF, 1024 * 1024);
        server.bind(port).syncUninterruptibly()
                .addListener((ChannelFutureListener) channelFuture -> {
                    if (channelFuture.isSuccess()) {
                        if (logger.isInfoEnabled()) {
                            logger.info("UDP服务端启动成功，端口号：" + port);
                        }
                    } else {
                        if (logger.isInfoEnabled()) {
                            logger.info("UDP服务端启动失败，端口号：" + port);
                        }
                    }
                });
    }

    public static void main(String[] args) {
        UDPServer udpServer = new UDPServer(9991);
        udpServer.buildServer();
    }
}
